package com.xyzwps.paimon.furina.common.jackson

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.module.SimpleModule
import com.xyzwps.paimon.furina.common.DateTimeUtil
import kotlinx.datetime.LocalDateTime

object LocalDateTimeKDS {
    object Deserializer : JsonDeserializer<LocalDateTime>() {
        override fun deserialize(p: JsonParser, ctxt: DeserializationContext): LocalDateTime =
            DateTimeUtil.parseLocalDateTime(p.text)
    }

    object KayDeserializer : KeyDeserializer() {
        override fun deserializeKey(key: String, ctxt: DeserializationContext): Any =
            DateTimeUtil.parseLocalDateTime(key)
    }

    object Serializer : JsonSerializer<LocalDateTime>() {
        override fun serialize(value: LocalDateTime?, gen: JsonGenerator, serializers: SerializerProvider) {
            if (value == null) {
                gen.writeNull()
            } else {
                gen.writeString(DateTimeUtil.format(value))
            }
        }
    }

    fun SimpleModule.registerLocalDateTime() {
        this.addSerializer(LocalDateTime::class.java, Serializer)
        this.addDeserializer(LocalDateTime::class.java, Deserializer)
        this.addKeyDeserializer(LocalDateTime::class.java, KayDeserializer)
    }
}